package cn.liontalk.rabbitmqconsumer.directconsumer;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RabbitListener(queuesToDeclare = @Queue(RabbitMQConstant.RABBITMQ_DEMO_TOPIC))
public class RabbitMQConsumer {

    @Autowired
    ObjectMapper objectMapper;

    /**
     * 接收json数组
     * @param messageBytes
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void process(byte[] messageBytes, Message message, Channel channel) throws IOException {
        System.out.println("==============HelloWorld===============");
        //System.out.println(new String(messageBytes));
        // System.out.println(message.getMessageProperties().getMessageId());

        try {
//        ObjectMapper mapper = new ObjectMapper();
//        String messaged = new String(message.getBody(), "UTF-8");
//        long tag = message.getMessageProperties().getDeliveryTag();
//        byte[] bytes = message.getBody();
            User user = objectMapper.readValue(messageBytes, User.class);
            String result = new String(message.getBody());
            String messageId = message.getMessageProperties().getMessageId();
            System.out.println(result);
            System.out.println(user);
            System.out.println(messageId);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            e.printStackTrace();

        }

    }



}
